<template>
  <view class="container">
    <FilterNavbar>
      <template #center>
        <view class="navbar-title"> {{ pageTitle }} </view>
      </template>
    </FilterNavbar>
    <ve-form v-if="form" ref="ve_form" :model="form" :rules="rules">
      <ve-card title="车辆基本信息" type="none" fold v-model:initFold="foldStatus.fold1">
        <ve-form-item label="车牌号" :borderBottom="false" prop="licenseNo" required>
          <ve-input
            v-if="pageType != 'create' || pageFrom == 'short-order' || pageFrom == 'long-order' || pageFrom == 'carManagerList'"
            v-model="form.licenseNo"
            disabled
            :allowClear="false"
          />
          <remote-select
            v-else
            type="licenseNo"
            :label="form.licenseNo"
            @change="changeLicenseNo"
            :params="{ idList: form.carId ? [form.carId] : undefined }"
            v-model="form.carId"
          />
        </ve-form-item>
        <car-info v-if="record.licenseNo" :record="record" :pageType="pageType" :pageFrom="pageFrom" />
        <view :style="record.licenseNo ? 'height: 24rpx;' : ''"></view>
      </ve-card>
      <ve-card title="维修单信息" type="none" fold v-model:initFold="foldStatus.fold2" style="overflow: hidden">
        <ve-form-item label="维修单关联门店" prop="siteId" required>
          <remote-select
            type="site"
            v-model="form.siteId"
            :label="form.siteName"
            :params="{ oldId: form.siteId }"
            @change="changeSiteId"
            allowClear
          />
        </ve-form-item>
        <ve-form-item
          label="入厂时间"
          :prop="pageType == 'create' || pageType == '' ? '' : 'arrivalTime'"
          :required="pageType == 'create' || pageType == '' ? false : true"
        >
          <ve-date-picker v-model="form.arrivalTime" title="时间" @change="onConfirmArrivalTime" allowClear></ve-date-picker>
        </ve-form-item>

        <ve-form-item
          label="出厂时间"
          :prop="pageType == 'create' || pageType == '' ? '' : 'leaveTime'"
          :required="pageType == 'create' || pageType == '' ? false : true"
        >
          <ve-date-picker
            :disabled="!form.arrivalTime"
            v-model="form.leaveTime"
            title="时间"
            :minDate="minDate"
            allowClear
          ></ve-date-picker>
        </ve-form-item>

        <ve-form-item label="承租人信息">
          <remote-select
            :disabled="pageFrom == 'short-order' || pageFrom == 'long-order'"
            v-model="form.memberId"
            :mustParentTip="mustParentTip"
            type="member_order_list"
            :params="{
              oldId: form.memberId,
              carId: form.carId,
              orderTypeList: [2, 3], // 关联长租\短租
            }"
            :label="memberLabel"
            allowClear
            @change="memberChange"
          ></remote-select>
        </ve-form-item>

        <ve-form-item label="关联订单号">
          <remote-select
            :disabled="pageFrom == 'short-order' || pageFrom == 'long-order'"
            v-model="form.orderId"
            :mustParentTip="mustParentTip"
            type="orderCar"
            :params="{
              oldOrderId: form.orderId,
              oldOrderType: form.orderType,
              carId: form.carId,
              memberId: form.memberId,
              orderTypeList: [2, 3], // 关联长租\短租
              useAuth: 1,
            }"
            :label="form.orderNo"
            allowClear
            @change="orderChange"
          />
        </ve-form-item>

        <ve-form-item
          label="修理厂"
          :prop="pageType == 'create' || pageType == '' ? '' : 'repairShop'"
          :required="pageType == 'create' || pageType == '' ? false : true"
        >
          <remote-select
            :multiple="false"
            :type="remoteSelectData.attrs.type"
            v-model="form.repairShopId"
            v-model:label="remoteSelectData.label"
            allowClear
            :params="{
              id: form.repairShopId,
            }"
            @change="changesupplierMainId"
          ></remote-select>
        </ve-form-item>

        <ve-form-item label="入厂里程" unit="公里">
          <ve-input-number v-model="form.entranceKilometre" placeholder="请输入" />
        </ve-form-item>
        <ve-form-item
          label="出厂里程"
          unit="公里"
          :prop="pageType == 'end' || pageType === 'finish' ? 'exportKilometre' : ''"
          :required="pageType == 'end' || pageType === 'finish' ? true : false"
        >
          <ve-input-number v-model="form.exportKilometre" placeholder="请输入" />
        </ve-form-item>

        <ve-form-item
          label="负责人"
          :prop="pageType === 'end' || pageType === 'finish' ? 'undertakerId' : ''"
          :required="pageType === 'end' || pageType === 'finish' ? true : false"
        >
          <remote-select
            type="staff_all_bysite"
            @change="changeUndertaker"
            :mustParentTip="mustParentTip"
            :label="form.undertaker"
            v-model="form.undertakerId"
            :params="{ oldId: form.undertakerId, siteIdList: [record.siteId] }"
            allowClear
          />
        </ve-form-item>

        <ve-form-item label="备注" labelPosition="top">
          <ve-input type="textarea" v-model="form.remark" style="background: #eff0f2" placeholder="请输入备注" />
        </ve-form-item>
        <ve-form-item
          label="上传照片"
          labelPosition="top"
          :required="pageType === 'end' || pageType === 'finish' ? true : false"
          :prop="pageType === 'end' || pageType === 'finish' ? 'fileIdList' : ''"
        >
          <ve-upload v-model="form.fileIdList"></ve-upload>
        </ve-form-item>

        <!-- 维修内容 -->
        <ve-form-item label="维修项目" :unit="pageType === 'finish' ? '' : 'arrowRight'" :borderBottom="false">
          <view class="c2 fs28" style="float: right" @click="chooseMain" v-if="pageType !== 'finish'">请选择</view>
        </ve-form-item>
        <Projects :pageType="pageType" :record="form" />
        <view :style="form.detailList && form.detailList.length ? 'height: 24rpx' : ''"></view>
      </ve-card>
    </ve-form>
    <ve-bottom-box size="mini">
      <ve-button type="primary" size="long" :loading="okLoading" @click="formSubmit">确认</ve-button>
    </ve-bottom-box>
  </view>
</template>

<script setup>
  import { onLoad, onUnload } from '@dcloudio/uni-app'
  import { ref, computed, provide, watch, nextTick } from 'vue'
  import FilterNavbar from '@/components/FilterNavbar'
  import Projects from './components/projects.vue'
  import { getDetailApi, createApi, editApi } from '@/api/asset/car-repair'
  import { orderCarInfo } from '@/api/asset/car-manager'
  import CarInfo from '../detail/components/carInfo.vue'
  import useFormFold from '@/hooks/useFormFold'
  import { findOrder } from '@/api/asset/car-violation'
  import { useLoadDataAndHotUpdateNavigateBack } from '@/hooks/useListNavigate'
  import dayjs from 'dayjs'
  import { findUserInfo } from '@/api/common'

  const userInfo = ref({})

  const { foldStatus, foldValidate } = useFormFold([
    {
      key: 'fold1',
      props: ['licenseNo'],
    },
    {
      key: 'fold2',
      props: ['siteId', 'arrivalTime', 'leaveTime', 'repairShop', 'exportKilometre', 'undertakerId', 'fileIdList'],
    },
  ])
  const rules = ref({
    licenseNo: {
      required: true,
      message: '请选择车牌号',
    },
    siteId: {
      required: true,
      message: '请选择维修单关联门店',
    },
    arrivalTime: {
      required: true,
      message: '请选择入厂时间',
    },
    leaveTime: {
      required: true,
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请选择出厂时间'))
        } else if (value && dayjs(value).startOf('minute').valueOf() === dayjs(form.value.arrivalTime).startOf('minute').valueOf()) {
          callback(new Error('出厂时间不能等于入厂时间'))
        } else {
          callback()
        }
      },
    },
    repairShop: {
      required: true,
      message: '请选择修理厂',
    },
    exportKilometre: {
      required: true,
      message: '请输入出厂里程',
    },
    undertakerId: {
      required: true,
      message: '请选择负责人',
    },
    fileIdList: {
      required: true,
      message: '请上传照片',
    },
  })
  const { statusBarHeight } = uni.getSystemInfoSync()
  const pageTitle = ref('维修')
  const form = ref({
    carId: '',
    detailList: [],
    arrivalTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    leaveTime: dayjs().add(1, 'days').format('YYYY-MM-DD HH:mm:ss'),
  })
  provide('form', form.value)
  const record = ref({})
  const pageType = ref(null) //create新增 edit编辑 start开始维修 end结束维修
  // const add = () => {uni.navigateTo({url: 'form/index'})}
  // onMounted(() => {
  //   loadData()
  // })

  const minDate = ref(dayjs(form.value.arrivalTime).add(1, 'minute').valueOf())

  // 选择入厂时间
  const onConfirmArrivalTime = (current) => {
    if (current) {
      if (current > form.value.leaveTime) {
        // 入厂时间改变并且大于出厂时间，出厂时间+1
        form.value.leaveTime = dayjs(form.value.arrivalTime).add(1, 'day').format('YYYY-MM-DD HH:mm:ss')
      }

      minDate.value = dayjs(current).add(1, 'minute').valueOf()
    } else {
      form.value.leaveTime = ''
    }
  }
  // 去选择保养项目
  const chooseMain = () => {
    var ids = []
    if (form.value.detailList && form.value.detailList.length) {
      form.value.detailList.forEach((i) => {
        ids.push(i.repairItemId)
      })
    }
    uni.navigateTo({
      url: '/pages/asset/car-repair/components/projectList?ids=' + JSON.stringify(ids),
    })
  }
  // 选完保养项目后
  uni.$on('getMainlists', function (data) {
    var mainlists = data
    console.log('form.value.detailList', data)
    var arr = form.value.detailList
    if (mainlists && mainlists.length) {
      mainlists.forEach((el, index) => {
        if (arr && arr.length) {
          arr.forEach((ol) => {
            if (el.repairItemId == ol.repairItemId) {
              el = ol
              mainlists.splice(index, 1, ol)
            }
          })
        }
      })
    }
    setTimeout(() => {
      // console.log('eeeee', mainlists)
      nextTick(() => {
        form.value.detailList = mainlists
      })
    }, 300)
  })
  // 选择车牌号
  const changeLicenseNo = (a, option = {}) => {
    form.value.carId = a
    form.value.licenseNo = option.licenseNo
    form.value.siteId = option.siteId
    form.value.siteName = option.siteName
    record.value = option
    form.value.entranceKilometre = option.totalMileage //选车牌号自动带入入厂里程

    if (!form.value.undertakerId) {
      form.value.undertakerId = userInfo.value.employeeId
      form.value.undertaker = userInfo.value.realname
    }

    // 切换车牌，清空订单、承租人信息
    form.value.orderId = undefined
    form.value.orderNo = undefined
    form.value.memberId = undefined
    form.value.memberName = undefined
    form.value.memberPhone = undefined
  }
  const getDetail = async (id) => {
    const res = await getDetailApi({ id: id })
    form.value = res.result
    form.value.arrivalTime = res.result.arrivalTime ?? undefined
    form.value.leaveTime = res.result.leaveTime ?? undefined
    form.value.detailList = res.result.detailList ?? []
    minDate.value = dayjs(form.value.arrivalTime).add(1, 'minute').valueOf()

    if ((pageType.value == 'end' || pageType.value == 'finish') && !form.value.undertakerId) {
      form.value.undertakerId = userInfo.value.employeeId
      form.value.undertaker = userInfo.value.realname
    }

    record.value = res.result
    remoteSelectData.label = res.result.repairShop
  }
  const changesupplierMainId = (a, option = {}) => {
    form.value.repairShopId = a
    form.value.repairShop = option.supplierName
  }
  const changeUndertaker = (a, option = {}) => {
    form.value.undertakerId = a
    form.value.undertaker = option.realname
  }
  // 获取订单详情=>获取车信息和订单信息
  const getOrderCarInfo = (id, type) => {
    orderCarInfo({ id: id, type: type }).then((res) => {
      form.value.licenseNo = res.result.licenseNo
      form.value.carId = res.result.carId
      form.value.orderType = res.result.type
      record.value.licenseNo = res.result.licenseNo
      record.value.vin = res.result.vin
      record.value.modelName = res.result.modelName
      record.value.siteName = res.result.siteName
      record.value.libraryName = res.result.libraryName
      record.value.orderNo = res.result.orderCode

      // 承租人信息
      form.value.memberId = res.result.memberId
      form.value.memberName = res.result.memberName
      form.value.memberPhone = res.result.memberPhone
      // 订单信息
      form.value.orderId = res.result.orderId
      form.value.orderNo = res.result.orderCode
      // 门店信息
      form.value.siteId = res.result.siteId
      form.value.siteName = res.result.siteName

      if (!form.value.undertakerId) {
        form.value.undertakerId = userInfo.value.employeeId
        form.value.undertaker = userInfo.value.realname
      }
    })
  }

  // 获取员工登录信息
  const getUserInfoApi = () => {
    return new Promise((resolve, reject) => {
      findUserInfo({})
        .then((res) => {
          const data = res.result
          userInfo.value = data
          resolve()
          console.log('userInfo', userInfo.value)
        })
        .catch((err) => {
          reject(err)
        })
    })
  }

  const pageFrom = ref()
  const optionsConfig = ref()
  onLoad((options) => {
    console.log('options', options)
    optionsConfig.value = options

    getUserInfoApi().then(() => {
      if (options.origin == 'short-order') {
        pageFrom.value = options.origin
        pageType.value = 'create'
        pageTitle.value = '新增维修单'
        form.value.carId = options.carId

        // 获取车辆信息
        form.value.orderType = 2
        // pagefromReturnCar.value = true
        form.value.orderId = options.orderId
        getOrderCarInfo(form.value.orderId, 2)
      } else if (options.origin == 'long-order') {
        pageFrom.value = options.origin
        pageType.value = 'create'
        pageTitle.value = '新增维修单'
        form.value.carId = options.carId

        // 获取车辆信息
        form.value.orderType = 3
        // pagefromReturnCar.value = true
        form.value.orderId = options.orderId
        getOrderCarInfo(form.value.orderId, 3)
      } else {
        pageType.value = options.pageType
        pageFrom.value = options.origin
        if (options.id) {
          getDetail(options.id)
        }
        if (pageType.value == 'start') {
          pageTitle.value = '开始维修'
        } else if (pageType.value == 'end') {
          pageTitle.value = '完成维修'
        } else if (pageType.value == 'create') {
          pageTitle.value = '新增维修单'
        } else {
          pageTitle.value = '编辑维修单'
        }
      }
      // 处理修理厂必填rules
      if (pageType.value == 'create' || pageType.value == '') {
        rules.value.repairShop.required = false
      }
      // 车辆管理列表新增维修，不允许编辑车牌号
      if (options.licenseNo) form.value.licenseNo = options.licenseNo
      if (options.carId) form.value.carId = options.carId
    })
  })
  defineExpose({
    // getMainLists,
    // updateCarInfo,
  })
  const toast = (text) => {
    uni.showToast({
      icon: 'none',
      title: text,
    })
  }
  const edit = (params) => {
    okLoading.value = false
    editApi(params)
      .then((res) => {
        if (res.code == 200) {
          toast(res.message)
          okLoading.value = false
          useLoadDataAndHotUpdateNavigateBack()
        } else {
          toast(res.message)
          okLoading.value = false
          return false
        }
      })
      .catch((_) => {
        okLoading.value = false
      })
  }
  const remoteSelectData = {
    prop: 'repairShopId',
    label: '',
    type: 'remote-select',
    attrs: {
      type: 'supplierRepair',
    },
  }
  // 必填提示
  const mustParentTip = computed(() => {
    if (!form.value.carId) return '请选择车牌号'
    return ''
  })

  // 承租人label
  const memberLabel = computed(() => {
    if (form.value.memberName || form.value.memberPhone) {
      return [form.value.memberName, form.value.memberPhone].join('|')
    } else {
      return ''
    }
  })

  // 承租人change
  const memberChange = (val, option) => {
    if (val) {
      form.value.memberId = val
      form.value.memberName = option.memberName
      form.value.memberPhone = option.phone

      // 需要获取最新的车牌号信息
      selectLinkedOrder()
    } else {
      form.value.memberId = undefined
      form.value.memberName = undefined
      form.value.memberPhone = undefined
    }
  }

  const selectLinkedOrder = () => {
    findOrder({
      carId: form.value.carId,
      memberId: form.value.memberId,
      orderTypeList: [2, 3], // 关联长租\短租
      useAuth: 1,
    }).then((res) => {
      if (res.code == 200) {
        const orderList = res.result
        if (orderList.length > 0) {
          // 当前存在已选择的订单时，判断是否需要清空
          let defaultSelectFirst = true
          if (form.value.orderId) {
            const hasSameOrderId = orderList.some((item) => item.orderId == form.value.orderId)
            if (hasSameOrderId) {
              // 存在相同订单，则不再默认选中第一个
              defaultSelectFirst = false
            }
          }
          if (defaultSelectFirst) {
            const order = orderList[0]
            form.value.orderId = order.orderId
            form.value.orderNo = order.orderNo
            form.value.orderType = order.orderType

            form.value.memberId = order.memberId
            form.value.memberPhone = order.memberPhone
            form.value.memberName = order.memberName
          }
        } else {
          // 清空订单信息
          form.value.orderId = undefined
          form.value.orderNo = undefined
          form.value.orderType = undefined
        }
      }
    })
  }
  // 自动选中维修订单 end
  // 订单change
  const orderChange = (val, option) => {
    if (val) {
      form.value.orderNo = option.orderNo
      form.value.orderType = option.orderType

      // 更新承租人信息
      form.value.memberId = option.memberId
      form.value.memberPhone = option.memberPhone
      form.value.memberName = option.memberName
    } else {
      form.value.orderNo = undefined
      form.value.orderType = undefined
    }
  }
  const okLoading = ref(false)
  const ve_form = ref(null)
  const formSubmit = () => {
    okLoading.value = true
    ve_form.value.validate((valid, errors) => {
      if (valid) {
        var res
        var params = {
          ...form.value,
        }
        if (pageType.value == 'start') {
          params.status = 1
          edit(params)
        } else if (pageType.value == 'end') {
          params.status = 2
          edit(params)
        } else if (pageType.value == 'create') {
          params.status = 0
          createApi(params)
            .then((res) => {
              okLoading.value = false
              if (res.code == 200) {
                toast(res.message)
                okLoading.value = false
                // 车辆管理列表增加保养成功后，跳转至保养列表
                if (pageFrom.value == 'carManagerList') {
                  uni.redirectTo({
                    url: `/pages/asset/car-manager/detail/repair-record?id=${form.value.carId}`,
                  })
                } else {
                  useLoadDataAndHotUpdateNavigateBack()
                }
              } else {
                toast(res.message)
                okLoading.value = false
                return false
              }
            })
            .catch((_) => {
              okLoading.value = false
            })
        } else {
          // 编辑
          edit(params)
        }
      } else {
        foldValidate(errors)
        okLoading.value = false
        console.log('验证失败', errors)
      }
    })
  }

  // 自动选中维修订单 before
  watch(
    () => form.value.carId,
    (val) => {
      // 只有从维修列表新增的来源时使用这个逻辑（长租、短租列表的新增也需要避免这个逻辑）
      if (
        val &&
        pageFrom.value != 'short-order' &&
        pageFrom.value != 'long-order' &&
        pageType.value != 'start' &&
        pageType.value != 'end' &&
        !optionsConfig.value.id
      ) {
        selectLinkedOrder()
      }
    },
  )
  // 关联门店
  const changeSiteId = (a, option = {}) => {
    console.log(a)
    console.log(option)
    form.value.siteId = a
    form.value.siteName = option.siteName
  }

  onUnload(() => {
    uni.$off('getMainlists')
  })
</script>

<style lang="scss" scoped>
  .container {
    height: auto;
    padding: 24rpx 24rpx;
    background: #f7f8fa;
  }
</style>
